package com.wqj.kyee.gps.bluetooth

import android.app.FragmentManager
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.ListView
import android.widget.Toast
import com.wqj.kyee.gps.R
import com.wqj.kyee.gps.bluetooth.server.ConnectionManager
import com.wqj.kyee.gps.bluetooth.server.ConnectionService
import org.jetbrains.anko.find
import org.jetbrains.anko.setContentView
import java.lang.ref.WeakReference


class BtDevicesActivity : AppCompatActivity(), ConnectionManager.ConnectStateListener{
    override fun connectFail(bluetoothDevice: BluetoothDevice?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun connectSuccess(bluetoothDevice: BluetoothDevice?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun disconnectSuccess(bluetoothDevice: BluetoothDevice) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    lateinit var mHandler: MyHandler
    var mlistView: ListView? = null
    var menu: Menu? = null
    var discoveredBTDevices: ArrayList<BluetoothDeviceDean> = ArrayList() // 扫描到的bt device
    var btBroadcastReceiver:BtBroadcastReceiver?=null

    var instance:Context?=null;

    //lateinit var mActionBar : android.app.ActionBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        instance =this;
        btDevicesAdapter = BtDevicesAdapter(discoveredBTDevices, this)
        BtDevicesUi().setContentView(this@BtDevicesActivity)
//        if (!bluetoothAdapter.isEnabled) {
//            bluetoothAdapter.enable()
//            Log.d("wqj", "enable")
//        } else {
//            Log.d("wqj", "discovery")
//        }

        val actionBar = supportActionBar
        actionBar?.setHomeButtonEnabled(true)
        actionBar?.setDisplayHomeAsUpEnabled(true)

        mlistView = find<ListView>(BtDevicesUi.ID_BT_DEVICES_LIST)
        mHandler = MyHandler(this,discoveredBTDevices)

        mlistView?.setOnItemClickListener(object : OnItemClickListener {

            override fun onItemClick(arg0: AdapterView<*>, arg1: View?, arg2: Int,
                                     arg3: Long) {
                Log.i("wqj", "id: " + arg2)
//                if(null != BtClientThread.btClientThread && BtClientThread.btClientThread!!.isContected()){
//                    BtClientThread.btClientThread?.cancel();
//                }else{
//                    BtClientThread(discoveredBTDevices[arg2], mHandler).start()
//                }
                var connectionManager  = ConnectionManager.getInstance();
                if(connectionManager.isConnected){
                    connectionManager.cancel();
                }else{
                    var intent = Intent(instance, ConnectionService::class.java);
                    intent.putExtra("key","connect")
                    intent.putExtra("btdevice",discoveredBTDevices[arg2].bluetoothDevice)
                    startService(intent)
                }

            }
        })
    }

    override fun onStart() {
        super.onStart()
        ConnectionManager.getInstance().handler = mHandler;
        val filter = IntentFilter()
        filter.addAction(BluetoothDevice.ACTION_FOUND)
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        btBroadcastReceiver =BtBroadcastReceiver(this)
        registerReceiver(btBroadcastReceiver, filter)
        discoveredBTDevices.clear()
        bluetoothAdapter.startDiscovery()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        getMenuInflater().inflate(R.menu.bt_menu, menu);
        return super.onCreateOptionsMenu(menu)
    }

//    override fun onPrepareOptionsMenu(menu: Menu?) {
//        checkBtStatus()
//        super.onPrepareOptionsMenu(menu)
//    }

    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        this.menu = menu
        checkBtStatus()
        return super.onPrepareOptionsMenu(menu)
    }

    fun checkBtStatus() {
        if(!bluetoothAdapter.isEnabled()){
            var mi = menu?.findItem(R.id.open)
            mi?.setVisible(true)
            mi = menu?.findItem(R.id.close)
            mi?.setVisible(false)
        }else{
            var mi = menu?.findItem(R.id.close)
            mi?.setVisible(true)
            mi = menu?.findItem(R.id.open)
            mi?.setVisible(false)
        }
        val sharedPreferences = getSharedPreferences("bt-gps", Context.MODE_PRIVATE)
        val isAutoConnect = sharedPreferences.getBoolean("auto-connect", false)

        if(!isAutoConnect){
            var mi = menu?.findItem(R.id.autoconnect)
            mi?.setVisible(true)
            mi = menu?.findItem(R.id.noautoconnect)
            mi?.setVisible(false)
        }else{
            var mi = menu?.findItem(R.id.noautoconnect)
            mi?.setVisible(true)
            mi = menu?.findItem(R.id.autoconnect)
            mi?.setVisible(false)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        var id = item?.itemId;
        if (id == android.R.id.home) {
            val fm = fragmentManager
            if (fm.backStackEntryCount > 0) {
                fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
            } else {
                finish()
            }
        }
        if(id == R.id.open){
            bluetoothAdapter.enable()
            discoveredBTDevices.clear()
            btDevicesAdapter.notifyDataSetChanged()
//            unregisterReceiver(BtBroadcastReceiver(this))
//            val filter = IntentFilter()
//            filter.addAction(BluetoothDevice.ACTION_FOUND)
//            filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
//            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
//            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
//            registerReceiver(BtBroadcastReceiver(this), filter)
//            bluetoothAdapter.startDiscovery()
        }
        if(id == R.id.close){
            var connectionManager  = ConnectionManager.getInstance();
            if(connectionManager.isConnected){
                connectionManager.cancel();
            }
            discoveredBTDevices.clear()
            btDevicesAdapter.notifyDataSetChanged()
            bluetoothAdapter.cancelDiscovery()
            bluetoothAdapter.disable()

        }

        if(id == R.id.autoconnect){
            val sp = getSharedPreferences("bt-gps", Context.MODE_PRIVATE)
            val editor = sp.edit()
            editor.putBoolean("auto-connect", true)
            editor.commit()
            val isAutoConnect = sp.getBoolean("auto-connect", false)
            Log.e("wangrui","autoconnect" + isAutoConnect.toString())
            checkBtStatus()
        }
        if(id == R.id.noautoconnect){
            val sp = getSharedPreferences("bt-gps", Context.MODE_PRIVATE)
            val editor = sp.edit()
            editor.putBoolean("auto-connect", false)
            editor.commit()
            val isAutoConnect = sp.getBoolean("auto-connect", false)
            Log.e("wangrui","noautoconnect" + isAutoConnect.toString());

            checkBtStatus()
        }

        return super.onOptionsItemSelected(item)
    }

    override fun onStop() {
        super.onStop()
        ConnectionManager.getInstance().handler = null;
        bluetoothAdapter.cancelDiscovery()
        unregisterReceiver(btBroadcastReceiver)
    }


//    override fun onBackPressed() {
////        super.onBackPressed()
//
//        Toast.makeText(this, BtClientThread.btClientThread?.isContected().toString(), Toast.LENGTH_SHORT).show()
//    }




    public class MyHandler(activity: BtDevicesActivity,discoveredBTDevices:ArrayList<BluetoothDeviceDean>) : Handler() {

        //对Activity的弱引用
        private val mActivity: WeakReference<BtDevicesActivity>
        private var discoveredBTDevicesL: ArrayList<BluetoothDeviceDean> = discoveredBTDevices

        init {
            mActivity = WeakReference<BtDevicesActivity>(activity)
        }
        override fun handleMessage(msg: Message) {
            val activity = mActivity.get()
            if (activity == null) {
                super.handleMessage(msg)
                return
            }
            when (msg.what) {
                BT_CLIENT_CONNECT_FAIL -> {
                    var text = "连接GPS蓝牙板失败!"
                    var btdevice = msg.data.getParcelable<BluetoothDevice>("btdevice")
                    if(null != btdevice) {
//                        var btd:BluetoothDevice=nul
                        for (btd in discoveredBTDevicesL) {

                            if (btd.bluetoothDevice == btdevice) {
                                btd.isContected = false
//                                activity.setDiscoveredBTDevices(discoveredBTDevicesL)
                                break;
                            }
                        }
                        btDevicesAdapter.notifyDataSetChanged();
                    }
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
                }
                BT_CLIENT_CONNECT_SUCCESS -> {
                    var btdevice = msg.data.getParcelable<BluetoothDevice>("btdevice")
                    if(null != btdevice){
//                        var btd:BluetoothDevice=nul
                        for(btd in discoveredBTDevicesL){

                            if(btd.bluetoothDevice == btdevice) {
                                btd.isContected = true
                                discoveredBTDevicesL.remove(btd)
                                discoveredBTDevicesL.add(0,btd);
//                                activity.setDiscoveredBTDevices(discoveredBTDevicesL)
                                break;
                            }
                        }

                        btDevicesAdapter.notifyDataSetChanged();

                    }
                    var text = "连接GPS蓝牙板成功!"
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
                }
                BT_SERVER_CONNECT_FAIL -> {
                    var text = "GPS蓝牙板连我失败!"
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
                }
                BT_SERVER_CONNECT_SUCCESS -> {
                    var text = "GPS蓝牙板连我成功!"
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
                }
                BT_SERVER_DISCONNECT_SUCCESS -> {
                    var text = "断开GPS蓝牙板成功!"
                    var btdevice = msg.data.getParcelable<BluetoothDevice>("btdevice")
                    if(null != btdevice) {
//                        var btd:BluetoothDevice=nul
                        for (btd in discoveredBTDevicesL) {

                            if (btd.bluetoothDevice == btdevice) {
                                btd.isContected = false
//                                activity.setDiscoveredBTDevices(discoveredBTDevicesL)
                                break;
                            }
                        }
                        btDevicesAdapter.notifyDataSetChanged();
                    }
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
                }
                else -> super.handleMessage(msg)
            }
        }
    }

     companion object{
        lateinit var btDevicesAdapter: BtDevicesAdapter
        // connect成功的socket, map activity中用来读取信息
        var connectedSock: BluetoothSocket? = null
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        val BT_DEVICE_NAME = "SUOXI"
        var is_bt_connected: Boolean = false
        //val BT_UUID = "00001101-0000-1000-8000-00805F9B34FB"
        val BT_UUID = "29913A2D-EB93-40cf-BBB8-DEEE26452197"
        val BT_SERVER_NAME = "bt-gps-server"
         val i = 0
         const val GPS_BOARD_DATA = 0
         const val BT_CLIENT_CONNECT_SUCCESS = 1
         const val BT_CLIENT_CONNECT_FAIL = 2
        val BT_SERVER_CONNECT_SUCCESS = 3
        val BT_SERVER_CONNECT_FAIL = 4
         const val BT_SERVER_DISCONNECT_SUCCESS = 5
        //var discoveredBTDevices: ArrayList<BluetoothDeviceDean> = ArrayList() // 扫描到的bt device
    }
}
